﻿using System;
using System.Collections.Generic;
using BusinessObjects.Entities.Base;
using NHibernate;
using NHibernate.Type;

namespace Data.NHibernateProvider
{
    public class CustomInterceptor : EmptyInterceptor
    {
        public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)
        {
            Timestamp timestamp = GetTimestamp(state, propertyNames);
            timestamp.Created = DateTime.UtcNow;
            return true;
        }

        public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState,
                                          string[] propertyNames, IType[] types)
        {
            Timestamp timestamp = GetTimestamp(currentState, propertyNames);
            timestamp.Updated = DateTime.UtcNow;
            return true;
        }

        private static Timestamp GetTimestamp(IList<object> state, string[] propertyNames)
        {
            var timestamp = state[Array.IndexOf(propertyNames, "Timestamp")] as Timestamp;

            if (timestamp == null)
            {
                timestamp = new Timestamp();
                state[Array.IndexOf(propertyNames, "Timestamp")] = timestamp;
            }

            return timestamp;
        }
    }
}